import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj/',
  timeout: 20000,
})

service.interceptors.request.use(
  (config) => {
    const { token } = useUserStore()

    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (error) => {
    ElMessage.error(error.response.data.message)
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response) => {
    if (response.data instanceof Blob) {
      return response.data
    }
    if (response.data.code !== 10000) {
      ElMessage.error(response.data.msg)
      return Promise.reject(response.data.msg)
    }

    return response.data.data
  },
  (error) => {
    ElMessage.error(error.response.data.msg)

    if (error.response.status === 401) {
      useUserStore().logout()
    }
    return Promise.reject(error)
  },
)

class Http {
  get<T>(url: string, params?: Object, config?: Object) {
    return service.get<null, T>(url, { params, ...config })
  }

  post<T>(url: string, data?: Object) {
    return service.post<null, T>(url, data)
  }

  put<T>(url: string, data?: Object) {
    return service.put<null, T>(url, data)
  }

  delete<T>(url: string, params?: Object) {
    return service.delete<null, T>(url, { params })
  }
}

export const http = new Http()
